package com.webex.ta.hydra.gui.table.cellrenderer;

import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.gui.table.ExpansionToggleBorder;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.geom.GeneralPath;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-8-19
 * Time: 12:06:41
 */
public class KeywordRenderer extends DefaultTableCellRenderer {

    private static final Color DEBUG_BG = new Color(99, 130, 191);

//    private static final Color ALL_PASS = new Color(0x77, 0xFF, 0x77);
    private static final Color ALL_PASS = new Color(186, 238, 186, 230);
//    private static final Color ALL_FAIL = new Color(0xFF, 0x77, 0x77);
    private static final Color ALL_FAIL = new Color(255, 194, 194, 230);
    private static final Color PARTIAL_FAIL = new Color(0xEE, 0x88, 0x44, 200);

    private Command command;


    public Component getTableCellRendererComponent(JTable table,
                                                   Object value, boolean isSelected, boolean hasFocus,
                                                   int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected,
                hasFocus, row, column);

        if (value instanceof Command) {
            command = (Command) value;
            setText(command.getKeyword());

            boolean error = command.getValidationInfo(column - 1) != null;
            setBorder(new ExpansionToggleBorder(command, table.getGridColor(), error));

            if (!command.isEnabled())
                this.setForeground(Color.gray);

            Color bg = null;
            if (command.hasTestResult()) {
                if (command.resultsAllFailed())
                    bg = ALL_FAIL;
                else if (command.resultsAllPassed())
                    bg = ALL_PASS;
                else
                    bg = PARTIAL_FAIL;
            }

            if (command.isInDebug())
                bg = DEBUG_BG;

            if (bg != null) {
                if (isSelected) {
                    bg = bg.darker();
                }
                setBackground(bg);
            }
        }
        return this;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        paintAnnotationTriangle(g);
    }

    private void paintAnnotationTriangle(Graphics g) {
        if (command.hasAnnotation()) {
            Graphics2D g2d = (Graphics2D)g;
            g2d.setColor(Color.red);
            g2d.fill(getTriangle());
        }
    }

    private Shape getTriangle() {
        GeneralPath path = new GeneralPath();
        Dimension size = getSize();
        path.moveTo(size.getWidth(), 1);
        path.lineTo(size.getWidth(), 7);
        path.lineTo(size.getWidth() -  6, 1);
        path.lineTo(size.getWidth(), 1);
        return path;
    }
}
